package com.iwhalecloud.uncc.mq.handler;

import com.iwhalecloud.uncc.common.SpringContext;
import com.iwhalecloud.uncc.dao.ArchiverDao;
import com.iwhalecloud.uncc.db.DatasourceContextHolder;
import com.iwhalecloud.uncc.domain.ArchiverMsg;
import com.iwhalecloud.uncc.domain.InsCollectServerArchiverMsg;
import com.iwhalecloud.uncc.mq.listener.IMqHandle;
import com.iwhalecloud.uncc.utils.ArchiverUtil;
import com.iwhalecloud.uncc.utils.CheckUtil;
import com.iwhalecloud.uncc.utils.HisUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author zq
 * @date 2021/10/26 17:30
 * @description InsCollectServerArchiverHandler
 */
@Slf4j
public class InsCollectServerArchiverHandler implements IMqHandle , ArchiverHandler{

    private ArchiverDao insCollectServerResRateArchiverDao;

    @Override
    public void init(Map<String, Object> params) throws Exception {
        insCollectServerResRateArchiverDao = (ArchiverDao) getBean("insCollectServerResRateArchiverDao");
    }

    private Object getBean(String beanName) {
        return SpringContext.getContext().getBean(beanName);
    }

    @Override
    public boolean dealMessage(List messages) {
        long s = System.currentTimeMillis();
        if (log.isInfoEnabled()) {
            log.info(Thread.currentThread().getName()+ "-InsCollectServerArchiverHandler开始消费"+messages.size()+"条InsCollectServerArchiverMsg");
        }

        ArchiverUtil.dealMessage(messages,InsCollectServerArchiverMsg.class,this);

        if (log.isInfoEnabled()) {
            log.info(Thread.currentThread().getName() + "消费完,耗时:" + ((System.currentTimeMillis() - s) / 1000) + "s");
        }
        return true;
    }

    @Override
    public void dealArchiverMsg(ArchiverMsg msg) {
        this.dealArchiverMsg((InsCollectServerArchiverMsg)msg);
    }


    private void dealArchiverMsg(InsCollectServerArchiverMsg msg) {
        if(msg.getInsCollectServerList() == null){
            return;
        }
        doArchive(msg);
        isDeleteOnline(msg);
    }

    private void doArchive(InsCollectServerArchiverMsg msg) {
        CheckUtil.batchInsert(insCollectServerResRateArchiverDao, msg.getInsCollectServerResRateList(),
                HisUtil.changeHisDatasource(msg.getPartitionCode()));

    }

    private void isDeleteOnline(InsCollectServerArchiverMsg msg) {
        //切换oldPartitionCode 修改删除
        DatasourceContextHolder.setDs(msg.getPartitionCode());
        if (msg.getIsDeleteOnline()) {
            CheckUtil.batchDelete(insCollectServerResRateArchiverDao, msg.getInsCollectServerResRateList());
        } else {
            CheckUtil.batchUpdateArchived(insCollectServerResRateArchiverDao, msg.getInsCollectServerResRateList());
        }
    }
}
